package com.macro.mall.product.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.product.constant.Constants;
import com.macro.mall.product.service.PmProdStockTaskService;
import com.macro.mall.product.util.TaskUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class PmProdStockTaskServiceImpl implements PmProdStockTaskService {

    @Autowired
    private PmProdStockSetMapper pmProdStockSetMapper;
    @Autowired
    private PmProdStockTempTaskMapper pmProdStockTempTaskMapper;
    @Autowired
    private PmProdStockIoRecordMapper pmProdStockIoRecordMapper;
    @Autowired
    private PmProdStockMapper pmProdStockMapper;
    @Autowired
    private PmProdReleaseAreaMapper prodReleaseAreaMapper;


    /**1.获取指定时间内需要执行的库存数据，创建子任务**************************************/
    public void initCycleStock(){
        initStockTaskDaily();
    }
    /**2.每次获取一组待执行子任务，生成库存记录********************************************/
    public void handleStockTaskData(){
        /**1.获取待执行子任务数据集合***/
        int num = Constants.HANDLE_MAX_STOCK_TASK_NUM;
        PageHelper.startPage(1  , num);

        PmProdStockTempTaskExample example ;
        PmProdStockTempTaskExample.Criteria criteria ;
        example  = new PmProdStockTempTaskExample();
        criteria = example.createCriteria();
        criteria.andTaskStatusEqualTo(Constants.STOCK_TASK_STATUS_WAITING);
        List<PmProdStockTempTask> taskList = pmProdStockTempTaskMapper.selectByExample(example);

        /**2.更新数据状态***/
        List<PmProdStockTempTask> processingList = new ArrayList<PmProdStockTempTask>();
        if(taskList!=null && taskList.size()>0){
            PmProdStockTempTask upTask;
            int count;
            for(PmProdStockTempTask task : taskList){
                //将任务更新成处理中
                upTask = new PmProdStockTempTask();
                upTask.setId(task.getId());
                upTask.setTaskStatus(task.getTaskStatus());
                count = this.updateStockTaskStatusByKey(upTask,Constants.STOCK_TASK_STATUS_PROCESSING);
                if(count>0){
                    task.setTaskStatus(Constants.STOCK_TASK_STATUS_PROCESSING);
                    processingList.add(task);
                }
            }
        }
        /**3.数据处理************/
        if(processingList!=null && processingList.size()>0){
            Date curDate = new Date();
            PmProdStockTempTask upTask;
            for(PmProdStockTempTask task : taskList){
                this.saveStock(task,curDate);

                //将任务更新成已处理
                upTask = new PmProdStockTempTask();
                upTask.setId(task.getId());
                upTask.setTaskStatus(task.getTaskStatus());
                this.updateStockTaskStatusByKey(upTask,Constants.STOCK_TASK_STATUS_SUCCESS);
            }
        }
    }
    private void initStockTaskDaily(){

        /**1.获取日期集合***/
        int days = Constants.GENERATE_STOCK_TASK_DAY;
        List<String> dayList = new ArrayList<String>();
        for (int i = 0; i < days; i++) {
            dayList.add(TaskUtils.getDateAddDays(i));
        }
        /**2.1 构造子任务数据集合***/
        PmProdStockSet query = new PmProdStockSet();
        query.setType(Constants.STOCK_TASK_TYPE_DAILY);
        List<PmProdStockSet> prodStockSetList = pmProdStockSetMapper.selectBySelective(query);
        PmProdStockTempTask task;
        List<PmProdStockTempTask> taskList = new ArrayList<PmProdStockTempTask>();
        if(prodStockSetList!=null && prodStockSetList.size()>0){
            for(PmProdStockSet stockSet : prodStockSetList){

                for(String stockDate : dayList) {
                    task = new PmProdStockTempTask();
                    task.setType(stockSet.getType());
                    task.setStockDate(stockDate);
                    task.setStockTime(stockSet.getStockTime());
                    task.setTaskStatus(Constants.STOCK_TASK_STATUS_WAITING);
                    task.setStockSetId(stockSet.getId());
                    taskList.add(task);
                }
            }
        }
        /**2.2 构造上门服务子任务数据集合***/
        query = new PmProdStockSet();
        query.setType(Constants.STOCK_TASK_TYPE_DAILY_DOOR);
        prodStockSetList = pmProdStockSetMapper.selectBySelective(query);
        if(prodStockSetList!=null && prodStockSetList.size()>0){
            for(PmProdStockSet stockSet : prodStockSetList){
                for(String stockDate : dayList) {
                    task = new PmProdStockTempTask();
                    task.setType(stockSet.getType());
                    task.setStockDate(stockDate);
                    task.setStockTime(stockSet.getStockTime());
                    task.setTaskStatus(Constants.STOCK_TASK_STATUS_WAITING);
                    task.setStockSetId(stockSet.getId());
                    taskList.add(task);
                }
            }
        }
        /**3.保存数据***/
        if(taskList!=null && taskList.size()>0){
            long count;
            PmProdStockTempTaskExample example ;
            PmProdStockTempTaskExample.Criteria criteria ;
            for(PmProdStockTempTask taskDB : taskList){
                example  = new PmProdStockTempTaskExample();
                criteria = example.createCriteria();

                criteria.andStockDateEqualTo(taskDB.getStockDate());
                criteria.andStockTimeEqualTo(taskDB.getStockTime());
                criteria.andStockSetIdEqualTo(taskDB.getStockSetId());
                count= pmProdStockTempTaskMapper.countByExample(example);
                if(count==0){
                    try {
                        pmProdStockTempTaskMapper.insert(taskDB);
                    }catch (Exception e){
                        log.error("创建库存任务失败：stockSetId="+taskDB.getStockSetId()+" stockDate="+taskDB.getStockDate()+" stockTime="+taskDB.getStockTime()+"  "+e.getMessage());
                    }
                }
            }
        }
    }
    private int updateStockTaskStatusByKey(PmProdStockTempTask record,Integer newStatus){
        return  pmProdStockTempTaskMapper.updateStockTaskStatusByKey(record,newStatus);
    }
    private void saveStock(PmProdStockTempTask task,Date curDate){
        PmProdStockSet  pmProdStockSet = pmProdStockSetMapper.selectByPrimaryKey(task.getStockSetId());

        if(pmProdStockSet!=null ){
            PmProdStock prodStock = new PmProdStock();
            prodStock.setChannelId(pmProdStockSet.getChannelId());
            prodStock.setChannelName(pmProdStockSet.getChannelName());
            prodStock.setDealershipId(pmProdStockSet.getDealershipId());
            prodStock.setDealershipName(pmProdStockSet.getDealershipName());
            prodStock.setProdId(pmProdStockSet.getProdId());
            prodStock.setProdCode(pmProdStockSet.getProdCode());

            prodStock.setProdName(pmProdStockSet.getProdName());
            prodStock.setProdSpecId(pmProdStockSet.getProdSpecId());
            prodStock.setSkuInstId(pmProdStockSet.getSkuInstId());
            prodStock.setSkuCode(pmProdStockSet.getSkuCode());
            prodStock.setSkuName(pmProdStockSet.getSkuName());

            prodStock.setType(pmProdStockSet.getType());
            prodStock.setStockDate(task.getStockDate());
            prodStock.setStockTime(pmProdStockSet.getStockTime());
            prodStock.setCurrentStock(pmProdStockSet.getTotalStock());
            prodStock.setTotalStock(pmProdStockSet.getTotalStock());
            prodStock.setSaleStock(0F);
            prodStock.setUnit(pmProdStockSet.getUnit());

            if(pmProdStockSet.getReleaseAreaId()!=null){
                PmProdReleaseArea releaseArea =prodReleaseAreaMapper.selectByPrimaryKey(pmProdStockSet.getReleaseAreaId());
                if(releaseArea!=null){
                    prodStock.setProvCode(releaseArea.getProvCode());
                    prodStock.setCityCode(releaseArea.getCityCode());
                    prodStock.setCountyCode(releaseArea.getCountyCode());
                }
            }

            //流水表
            PmProdStockIoRecord record = new PmProdStockIoRecord();
            record.setChannelId(pmProdStockSet.getChannelId());
            record.setChannelName(pmProdStockSet.getChannelName());
            record.setDealershipId(pmProdStockSet.getDealershipId());
            record.setDealershipName(pmProdStockSet.getDealershipName());
            record.setProdId(pmProdStockSet.getProdId());
            record.setProdCode(pmProdStockSet.getProdCode());
            record.setProdName(pmProdStockSet.getProdName());

            record.setSkuInstId(pmProdStockSet.getSkuInstId());
            record.setSkuCode(pmProdStockSet.getSkuCode());
            record.setSkuName(pmProdStockSet.getSkuName());
            record.setType(pmProdStockSet.getType());
            record.setStockDate(task.getStockDate());
            record.setStockTime(pmProdStockSet.getStockTime());
            record.setIoAmount(pmProdStockSet.getTotalStock());
            record.setUnit(pmProdStockSet.getUnit());

            record.setCreateTime(curDate);
            record.setIoType(Constants.STOCK_IO_TYPE_IN);

            pmProdStockMapper.insert(prodStock);

            record.setStockId(prodStock.getId());
            pmProdStockIoRecordMapper.insert(record);
        }
    }
}
